<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/03/14 jason wang
// +----------------------------------------------------------------------
namespace app\erp\logic;
use think\facade\Hook;
use think\DB;
use util\Tree;
use think\facade\Debug;
use think\facade\Cache;
/**
 * 优惠券领取
 * @package app\erp\model
 */
class CouponUserinfologic{
	/**
     * 我的优惠券
     * @author  dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function coupon_user($user_id, $use_type = 0, $price = 0){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id'  => $user_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            $map = [];//搜索处理
			$map[] = ['coupon_user', '=', $user_id];
			$map[] = ['coupon_status', '=', 0]; //未删除
			switch ($use_type) {
				case 1: //全部 可用的/不可用的(未开始,不可用)
					$map[] = ['coupon_etime', ['=', 0], ['>', time()], 'or'];//未过期
                    $map[] = ['coupon_ordercode', '=', 0];//已使用
					break;
				case 2: //已使用
					$map[] = ['coupon_ordercode', '>', 0];//已使用
					break;
				case 3: //已过期
					$map[] = ['coupon_ordercode', '=', 0];//未使用
					$map[] = ['coupon_etime', ['>', 0], ['<=', time()]];
					break;
			}
			$list = model('ErpCouponUseinfo') -> where($map) -> order('id desc') -> select();//获取列表
			$result_list = [];
			foreach($list as $key => $value){
				$coupon_info = controller('Couponlogic','logic') -> coupon_list($user_id, $value['coupon_id'], 1);//优惠券详情
				if($coupon_info['code'] == 200){
					$coupon_info = $coupon_info['data'][0];
					$rel_list = $coupon_info;//优惠券详情
					$rel_list['couponId'] 	        = (int)$value['id'];
					$rel_list['couponCode'] 	    = (string)$value['coupon_code'];
					$rel_list['couponUseType']      = $use_type == 0 ? 1 : $use_type;
					$rel_list['couponPeriodStime']  = $value['coupon_stime'];
					$rel_list['couponPeriodEtime']  = $value['coupon_etime'];
					if($value['coupon_etime'] > 0){ //有效期判断
                        $rel_list['couponPeriod'] = 1;
                    }

					// 1 可用 2已使用 3已过期 4未开始 5不可用(后台限制)
					if($rel_list['couponUseType'] == 1){
						if($value['coupon_stime'] > time()){
							$rel_list['couponUseType'] = 4;
						}
						if($coupon_info['couponIsuse'] == 0){
							$rel_list['couponUseType'] = 5;
						}
						if($coupon_info['couponPeriod'] == 1 && $value['coupon_etime'] <= time()){
							$rel_list['couponUseType'] = 3;
						}
						if($value['coupon_ordercode'] > 0 && $value['coupon_usetime'] > 0){
							$rel_list['couponUseType'] = 2;
						}
					}
					
					if($price == 0){
						$result_list[] = $rel_list;
					}
					if($price > 0 && $rel_list['couponValue'] < $price){
                        if($rel_list['couponUseCondition'] == 0){
                            $result_list[] = $rel_list;
                        }
                        if($rel_list['couponUseCondition'] == 1 && $rel_list['couponUseConditionNum'] <= $price){
                            $result_list[] = $rel_list;
                        }
					}
				}
			}
			
			$type_list = array_column($result_list, 'couponUseType');
			array_multisort($type_list, SORT_ASC, $result_list);

            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $result_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
	
	/**
     * 领取优惠券
     * @author  dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
	public function coupon_receive($user_id, $coupon_id, $coupon_get_type){
		 DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id'   		=> $user_id,
				'coupon_id' 		=> $coupon_id,
				'coupon_get_type' 	=> $coupon_get_type,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
			// 1. 是否领取
			// 2. 是否满足领取条件
			// 3. 优惠券是否发完
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$map = [];
			$map[] = ['coupon_id', '=', $coupon_id];
			$map[] = ['coupon_user', '=', 0];
			$receive_info = model('erp/ErpCouponUseinfo', 'model') -> where($map) -> find(); //取出空优惠券
			if(empty($receive_info)){
				DB::rollback();
				return array_out(-1005, 'error');//没有空的优惠券了
			}
			$id = $receive_info['id'];
			$map = [];
			$map['id'] 			= $id;
			$map['coupon_user'] = 0;
			
			$data = [];
			$data['coupon_getime'] 		= time();
			$data['coupon_user']   		= $user_id;
			$data['coupon_get_type']  	= $coupon_get_type;

			$res = model('erp/ErpCouponUseinfo', 'model') -> update($data, $map);
			if(!$res){
				DB::rollback();
				return array_out(-1005, 'error2');
			}
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			
			DB::commit();
            return array_out(200, 'success', $id);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
	}
	
	/**
     * 删除优惠券
     * @author  dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
	public function coupon_delete($user_id, $coupon_id){
		 DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id'   		=> $user_id,
				'coupon_id' 		=> $coupon_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$map = [];
			$map['id']   = $coupon_id;
			$map['coupon_user'] = $user_id;
			
			$data = [];
			$data['coupon_status'] 	= 1;
			$res = model('ErpCouponUseinfo') -> update($data, $map);
			if(!$res){
				DB::rollback();
				return array_out(-1005, 'error2');
			}
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
	}
}